package com.jjiang.bbmall.order.interceptor;


import com.jjiang.common.constant.AuthServerConstant;
import com.jjiang.common.vo.MemberEntityVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberEntityVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置controller的部分接口是无需登录的
        boolean match = new AntPathMatcher().match("/order/order/status/**", request.getRequestURI());
        if (match) {
            return true;
        }

        MemberEntityVo memberEntityVo = (MemberEntityVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (memberEntityVo != null) {
            // 已登录
            loginUser.set(memberEntityVo);
            return true;
        } else {
            // 未登录
            request.getSession().setAttribute("msg", "请先进行登录");
            response.sendRedirect("http://127.0.0.1:20000/login.html");
            return false;
        }
    }
}
